package com.ck.print.demo.printbridge.message.handler;

import com.ck.print.demo.printbridge.ErrorMsg;
import com.ck.print.demo.printbridge.MacAddressUtil;
import com.ck.print.demo.printbridge.PrintWebSocketClient;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;


@Slf4j
public class FinalMessageHandle extends AMessageHandle {
    private static final String AGENT_MAC = "agent.mac";

    public FinalMessageHandle(String clientInfo){
        super(clientInfo);
    }

    @Override
    public Boolean apply(Map<String, Object> dataMap, PrintWebSocketClient currentClient, PrintWebSocketClient friendClient) {
        //需要处理特殊处理监听类的消息，由于消息没有uid，这里向消息中加入mac
        dataMap.put(AGENT_MAC, MacAddressUtil.agentMac());
        handleMessage(gson.toJson(dataMap), currentClient, friendClient);
        return true;
    }

    // 业务消息处理逻辑
    private void handleMessage(String message, PrintWebSocketClient currentClient, PrintWebSocketClient friendClient) {
        // 根据实际业务需求处理消息
        try {
            if (!friendClient.isOpen()) {
                log.info("{}通道已关闭，等待重连", clientInfo);
            }
            log.info("{}发送消息：{}", clientInfo, message);
            friendClient.send(message);
        } catch (Exception e) {
            log.error("{}消息处理异常：{}", clientInfo, e.getMessage());
            currentClient.send(gson.toJson(new ErrorMsg(false, "message send failed, waiting auto connect, please!")));
        }
    }
}
